package com.zusmart.core.junit;

import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;

import com.zusmart.base.util.AnnotationUtils;
import com.zusmart.core.bean.annotation.Configuration;
import com.zusmart.core.context.ApplicationContext;
import com.zusmart.core.context.annotation.AnnotationApplicationContext;

public class ZuSmartRunner extends BlockJUnit4ClassRunner {

	private ApplicationContext applicationContext;

	public ZuSmartRunner(Class<?> klass) throws InitializationError {
		super(klass);
		if (!AnnotationUtils.hasAnnotation(klass, Configuration.class)) {
			new RuntimeException(String.format("missing @Configuration annotation %s", klass.getName())).printStackTrace();
			throw new InitializationError("error");
		}
		this.applicationContext = new AnnotationApplicationContext(klass);
	}
	
	@Override
	protected Object createTest() throws Exception {
		try {
			this.applicationContext.start();
			return this.applicationContext.getBean(this.getTestClass().getJavaClass());
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 测试结束后,释放applicationContext
	 */
	@Override
	protected Statement withAfterClasses(final Statement statement) {
		return new Statement() {
			@Override
			public void evaluate() throws Throwable {
				if (null != statement) {
					statement.evaluate();
				}
				if (null != applicationContext) {
					applicationContext.close();
				}
			}
		};
	}

}